﻿using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Abp.Runtime.Session;
using SingleUserMall.Adverts.Form;
using SingleUserMall.Adverts.VO;
using SingleUserMall.Authorization.Users;
using SingleUserMall.Common;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace SingleUserMall.Adverts
{
    [AbpAuthorize]
    public class AdvertManageAppService : SingleUserMallAppServiceBase, IAdvertManageAppService
    {
        private readonly IRepository<Advert, long> _advertRepository;
        public AdvertManageAppService(
             IRepository<Advert, long> advertRepository
            )
        {
            _advertRepository = advertRepository;
        }

        public async Task<AdvertManageVO> GetAdvertAsync(SingleId<long> form)
        {
            var advter = await _advertRepository.FirstOrDefaultAsync(form.Id);
            return advter.ToVO<Advert, AdvertManageVO>();
        }

        public async Task<PagedResultDto<AdvertManageVO>> GetAdvertsAsync(AdvertSearchForm form)
        {
            var query =  _advertRepository.GetAll()
                .WhereIf(!string.IsNullOrEmpty(form.Keywords), x => x.Name.Contains(form.Keywords))
                .OrderByDescending(x => x.CreationTime);
            return await query.ToPagedResultDtoAsync<Advert, AdvertManageVO>(form, (i, vo) =>
            {

            });
        }

        public async Task RemoveAdvertAsync(SingleId<long> form)
        {
            await _advertRepository.DeleteAsync(form.Id);
        }
       
        public async Task<AdvertManageVO> SaveItemAsync(AdvertForm form)
        {
            var id = form.Id;
            var advter = await _advertRepository.FirstOrDefaultAsync(id);
            if (advter != null)
            {
                advter = form.MapTo(advter);
                await _advertRepository.UpdateAsync(advter);
            }
            else
            {
                advter = form.MapTo<Advert>();
                id = await _advertRepository.InsertAndGetIdAsync(advter);
            }
            advter = await _advertRepository.FirstOrDefaultAsync(id);
            return advter.ToVO<Advert, AdvertManageVO>();
        }
    }
}
